package com.gali.mall.exception;

import com.gali.mall.common.ResultInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * 全局异常类
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    //日志输出
    private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object handleException(Exception e) {
        log.error("Default Exception: ", e);
        return ResultInfo.error(GaLiExceptionEnum.SYSTEM_ERROR);
    }

    @ExceptionHandler(GaLiException.class)
    @ResponseBody
    public Object handleImoocMallException(GaLiException e) {
        log.error("GaLiException: ", e);
        return ResultInfo.error(e.getCode(), e.getMsg());
    }
    //统一参数校验异常处理
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResultInfo handlerMethodExceptionArgumentNotValidException(MethodArgumentNotValidException e){
        log.error("MethodArgumentNotValidException",e);
        return handlerBindingResult(e.getBindingResult());
    }

    public ResultInfo handlerBindingResult(BindingResult result){
        ArrayList<String> list = new ArrayList<>();

        if(result.hasErrors()){
            List<ObjectError> allError =new ArrayList<>();
            allError=result.getAllErrors();
            for (ObjectError objectError : allError) {
                String defaultMessage = objectError.getDefaultMessage();
                list.add(defaultMessage);
            }
        }
        if(list.size()==0){//由于list已经初始化，也不可能等于null，因此需要进行长度判断
            return ResultInfo.error(GaLiExceptionEnum.PARAM_ERROR);
        }
        return  ResultInfo.error(GaLiExceptionEnum.PARAM_ERROR.getCode(),list.toString());
    }
}
